#!/usr/bin/python
##############################################################
#   Betamax SMS
#   By: Paul Kretek, pk@pugio.net, http://pugio.net/
#   License: MIT License, see license.txt
##############################################################
#   Enter recipients phone number in the field, or select 
#   a contact from the dropdown list, type your message and
#   click the send button. Sometimes the Betamax server returns
#   an error, but the SMS is delivered successfuly, this also
#   happens through web - nothing I can fix.
##############################################################
#   # vi /usr/share/applications/hildon/BetamaxSMS.desktop
#   [Desktop Entry]
#   Name=BetamaxSMS
#   GenericName=BetamaxSMS
#   Comment=Sends SMS with Voipcheap
#   Exec=betamax.py
#   Icon=qgn_toolb_messagin_send
#   Terminal=false
#   Type=Application
#   Categories=Communication;Extras;GTK;
#   StartupWMClass=betamax.py
##############################################################
import gtk, hildon, sys, osso, time, re, gobject
import os.path
import threading
import urllib
gtk.gdk.threads_init()

class HildonSMSWorld(hildon.Program):
  listStore = gtk.ListStore(str, str)
##############################################################
#   Config me
##############################################################  
  username = "myuser"
  password = "mypass"
  
  # enter your username here OR your verified number you have preset in the Windows Client.
  mynumber = "+49213432"
  
  # see the SMS instructions on the Betamax site
  url = "https://myaccount.VoipCheap.com/clx/sendsms.php"
  #url = "https://myaccount.VoipDiscount.com/clx/sendsms.php"
  #url = "https://myaccount.12voip.com/clx/sendsms.php"
  #url = "https://myaccount.sparvoip.de/clx/sendsms.php"
  # etc...
  
  # this is your dropdown list, you can add more contacts by following this schema
  listStore.insert(0, ['Some guy', '+49234'])
  listStore.insert(1, ['Some gal', '+491345'])
  listStore.insert(2, ['Somebody else', '+493456'])
  #listStore.insert(3, ['etc', '+49xxxx'])
##############################################################
# Done  
##############################################################

  def __init__(self):
    hildon.Program.__init__(self)    
    self.window = hildon.Window()
    self.add_window(self.window)

    self.window.set_title('BetamaxSMS')
    self.window.set_icon_name('qgn_toolb_messagin_send')
    
    self.window.connect("destroy", gtk.main_quit)
 
    vb = gtk.VBox()
    vb.set_spacing( 6)
    vb.set_border_width( 12)
    self.window.add( vb)

    tb = gtk.HBox()
    tb.set_spacing(6)
    vb.pack_start(tb, False)

    tel_icon = gtk.image_new_from_icon_name( 'qgn_addr_icon_details_phone', gtk.ICON_SIZE_BUTTON)
    tb.pack_start(tel_icon, False)

    self.mycontact = gtk.ComboBoxEntry(self.listStore)
    tb.pack_start(self.mycontact, True)

    self.message = gtk.TextView()
    self.message.set_wrap_mode( gtk.WRAP_WORD)
    frame = gtk.Frame()
    frame.set_shadow_type( gtk.SHADOW_IN)
    frame.add( self.message)
    vb.pack_start( frame, True)


    self.textbuffer = self.message.get_buffer()
    self.textbuffer.connect('changed', self._updateCount)

    self._add_menu()
    self._add_toolbar()
    self.window.show_all()
    
  def _getno(self):
      if not self.mycontact.get_active() == -1:
        theno = self.listStore[self.mycontact.get_active()][1]
      else:
        p = re.compile(r'^(\+[0-9]+)$')
        if p.search(self.mycontact.child.get_text()):
          theno = p.search(self.mycontact.child.get_text()).group(1)
        else:
          theno = None
      return theno

  def _updateCount(self, widget):
    charactersInText = self.textbuffer.get_char_count()
    self.tlbItmLabel.set_label( str(160 - charactersInText) )

  def _add_menu(self):
    menu = gtk.Menu()

    mnuItmSend = gtk.MenuItem("Send")
    mnuItmSend.connect("activate", self.send_sms)
    menu.add(mnuItmSend)

    mnuSpacer = gtk.SeparatorMenuItem()
    menu.add(mnuSpacer)
    mnuItmAbout = gtk.MenuItem("About")
    mnuItmAbout.connect("activate", self._show_about)
    menu.add(mnuItmAbout)
    mnuItmQuit = gtk.MenuItem("Quit")
    mnuItmQuit.connect("activate", gtk.main_quit)
    menu.add(mnuItmQuit)
    self.set_common_menu(menu)
    
  def _add_toolbar(self):
    toolbar = gtk.Toolbar()
    toolbar.expand = True
    self.tlbItmSend = gtk.ToolButton(label='Send')
    self.tlbItmSend.set_icon_name('qgn_toolb_messagin_send')    
    self.tlbItmSend.connect("clicked", self.send_sms)
    toolbar.insert(self.tlbItmSend, -1)
    
    self.tlbItmLabel = gtk.ToolButton(label='160')    
    toolbar.insert(self.tlbItmLabel, -1)

    self.set_common_toolbar(toolbar)
    toolbar.show_all()
  def _show_about(self, event):
    dlg = gtk.AboutDialog()
    dlg.set_version("0.1")
    dlg.set_name("BetamaxSMS")
    dlg.set_authors(["pakr from itt forums"])
    def close(w, res):
      if res == gtk.RESPONSE_CANCEL:
        w.hide()
    dlg.connect("response", close)
    dlg.show()

  def send_sms( self, widget):
      self.tlbItmSend.set_sensitive( False)
      threading.Thread( target = self.send_sms_thread).start()

  def send_sms_thread( self):
      buf = self.message.get_buffer()
      message = buf.get_text( buf.get_start_iter(), buf.get_end_iter())
      number = self._getno()
      if not number:
        self.tlbItmSend.set_sensitive( True)
        self.info_message( "Not a number" )
        return
      for message in self.send_message( number, message):
        gobject.idle_add( lambda: self.info_message( message ))
      self.tlbItmSend.set_sensitive( True)
      

  def info_message(self, message):
      osso_c = osso.Context("osso_test_note", "0.0.1", False)
      note = osso.SystemNote(osso_c)
      result = note.system_note_infoprint(message)

  def send_message( self, to, msg):
    yield "Sending..."
    msg = urllib.urlencode({"username": self.username, "password": self.password, "from": self.mynumber, "to": to, "text": msg})
    request = self.url + "?%s" % msg
    data = urllib.urlopen(request).read()
    print data
        
    p = re.compile(r'<description>(.*?)<\/description>')
    if p.search(data).group(1) == "":
      yield "Success"
    else:
      yield p.search(data).group(1)

  def run(self):
    gtk.main()
if __name__ == "__main__":
  app = HildonSMSWorld()
  app.run()